﻿using System;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace OA
{
    public partial class Login : Form
    {
        #region 用户常量、变量
        private const string CONFIG_FILE_PATH = "./OA.ini";
        public static string USERNAME;
        public static string PASSWORD;

        public delegate CookiesEntity GetLoginCookieDelegate(string username, string password);
        public delegate void SetTextDelegate(CookiesEntity text);
        //public delegate void VoidDelegate();
        #endregion
        public Login()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            LoginReady();
        }
        #region 开始登录一系列操作
        /// <summary>
        /// 开始登录
        /// </summary>
        private void LoginReady()
        {
            
            if (txtUsername.Text == string.Empty)
            {
                MessageBox.Show("用户名不能为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (txtPassword.Text == string.Empty)
            {
                MessageBox.Show("密码不能为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            btnLogin.Enabled = false;
            if (File.Exists(CONFIG_FILE_PATH))
            {
                //配置存在
                using (StreamWriter streamwriter = File.CreateText(CONFIG_FILE_PATH))
                {
                    streamwriter.Write("USERNAME=" + txtUsername.Text.Trim() + ";PASSWORD=" + txtPassword.Text.Trim());
                }
            }
            else
            {
                //配置不存在
                File.AppendAllText(CONFIG_FILE_PATH, "USERNAME=" + txtUsername.Text.Trim() + ";PASSWORD=" + txtPassword.Text.Trim(), Encoding.Default);
            }
            USERNAME = txtUsername.Text.Trim();
            PASSWORD = txtPassword.Text.Trim();
            //所有登录前的检查完毕，开始异步登录获取Cookies
            lblLoginInfo.Text = "正在登录中，请稍后……";
            GetLoginCookieDelegate getlogincookiedelegate = new GetLoginCookieDelegate(HttpHelper.GetLoginCookie);
            getlogincookiedelegate.BeginInvoke(USERNAME, PASSWORD, GetLoginCookieCallback, getlogincookiedelegate);
        }
        /// <summary>
        /// GetLoginCookieCallback
        /// </summary>
        /// <param name="async"></param>
        public void GetLoginCookieCallback(IAsyncResult async)
        {
            CookiesEntity cookiesentity = new CookiesEntity();
            GetLoginCookieDelegate dl = (GetLoginCookieDelegate)async.AsyncState;
            cookiesentity = dl.EndInvoke(async);
            cookiesentity.UserName = USERNAME;
            cookiesentity.Password = PASSWORD;
            //MessageBox.Show(cookies.GetCookie);
            if (lblLoginInfo.InvokeRequired)
            {
                SetTextDelegate settextdelegate = new SetTextDelegate(SetText);
                lblLoginInfo.Invoke(settextdelegate, cookiesentity);
            }
        }
        /// <summary>
        /// 设置文本属性的线程方法
        /// </summary>
        /// <param name="_cookies"></param>
        private void SetText(CookiesEntity _cookies)
        {
            if (_cookies.CookieStatus)
            {
                this.Close();
                //OAMain.OACookie = _cookies.GetCookie;
                OAMain.cookies = _cookies;
                OAMain oamain = (OAMain)this.Owner;
                oamain.Text = "当前用户：" + _cookies.UserName + " --- 技术预览版1.0";
                oamain.SetSession(_cookies.GetCookie);
                oamain.RunOne();
            }
            else
            {
                lblLoginInfo.Text = "用户名或密码不正确！";
            }
            btnLogin.Enabled = true;
        }
        #endregion

        private void Login_Load(object sender, EventArgs e)
        {
            LoginLoad();
        }
        #region 窗体初始化
        /// <summary>
        /// 初始化一些操作
        /// </summary>
        private void LoginLoad()
        {
            //加载界面基本信息
            this.Text = "输入用户信息登录";

            if (File.Exists(CONFIG_FILE_PATH))
            {
                //如果配置文件存在那就加载
                using (FileStream filestream = File.Open(CONFIG_FILE_PATH, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (StreamReader streamreader = new StreamReader(filestream, Encoding.Default))
                    {
                        try
                        {
                            string ini = streamreader.ReadToEnd();
                            txtUsername.Text = ini.Split(';')[0].Split('=')[1];
                            txtPassword.Text = ini.Split(';')[1].Split('=')[1];
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                    }
                }
            }
        }
        #endregion


        private void txtUsername_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtPassword.Focus();
                txtPassword.SelectAll();
            }
        }

        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnLogin.PerformClick();
            }
        }

    }
}
